import { Component, OnInit, OnDestroy, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { NavController, IonTabs, AlertController, ModalController, PopoverController, ActionSheetController, Platform, ToastController } from '@ionic/angular';
import { Subscription } from 'rxjs';

import { LocalNotifications } from '@ionic-native/local-notifications/ngx';
import { JPush } from '@jiguang-ionic/jpush/ngx';

import { GlobalService } from '../services/global.service';
import { DataService } from '@services/data.service';
import { CacheService } from '@services/cache.service';
import { NativeService } from '@services/native.service';
import { MessageService } from '@services/message.service';
import { Router, NavigationEnd } from '@angular/router';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AlarmAudioService } from '@services/alarmAudio.service';

declare var window;

@Component({
  selector: 'app-tabs',
  templateUrl: 'tabs.page.html',
  styleUrls: ['tabs.page.scss'],
})
export class TabsPage implements OnDestroy {
  @ViewChild('tabs') tabs: IonTabs;
  tabsCanGoBack = false;
  tabsParentCanGoBack = false;
  flag = 'home';
  Flag; // 是否语音告警
  alarmAccount: any;
  devicePlatform = 'Android';
  needAlarmNotify = true;
  subscription: Subscription;
  jpushSubscription;
  alarmInterval = null;
  backButtonPressed = false;
  tab1Root = 'home';
  // tab1Root;
  tab2Root = 'alarm';
  tab3Root = 'my';

  url;
  isUrl = false;  // 判断点击导航键的路由

  pages: any;

  constructor(
    public dataservice: DataService,
    public localNotifications: LocalNotifications,
    public jpush: JPush,
    public global: GlobalService,
    public cache: CacheService,
    public navCtrl: NavController,
    public native: NativeService,
    private messageService: MessageService,
    private router: Router,
    private alarmAudioService: AlarmAudioService,
    private statusBar: StatusBar,
    private ele: ElementRef,
    private renderer: Renderer2,
    public alertCtrl: AlertController,
    public modalCtrl: ModalController,
    public actionSheetCtrl: ActionSheetController,
    public popoverCtrl: PopoverController,
    private platform: Platform,
    private toastCtrl: ToastController
  ) {
    this.statusBar.overlaysWebView(true);
    if (this.cache.currentProject) {
      this.getAlarmAccount(this.cache.currentProject.projectId);
    }

    this.subscription = this.native.jpushServices.subscribe(res => {
      if (this.cache.voiceState === 'on') {
        const content = (res.extras.areaName + res.extras.deviceName + res.extras.alarmTypeName).toString();
        this.getAlarm(content);
      }
    });

    this.subscription = this.messageService.getMessage().subscribe(data => {
      console.log(data)
      if (data.id === 'projectChange' && data.data) {
        if (this.alarmInterval) {
          clearInterval(this.alarmInterval);
        }
        this.needAlarmNotify = true;
        this.getAlarmAccount(data.data.projectId);
        this.alarmInterval = setInterval(() => {
          this.getAlarmAccount(data.data.projectId);
        }, 10000);
      }
    });

    this.jpushSubscription = this.native.jpushMonitor.subscribe((event) => {
      let projectId;
      let projectName;
      console.log('告警推送打开界面', event)
      if (event && event.extras && event.extras.projectId) {
        projectId = event.extras.projectId;
      }
      if (event && event.extras && event.extras.projectName) {
        projectName = event.extras.projectName;
      } else {
        projectName = this.cache.currentProject.projectName;
      }
      const data = {
        projectId: projectId,
        projectName: projectName
      }
      this.cache.currentProject = data;
      this.navCtrl.navigateForward(['tabs/alarm'], {
        queryParams: {
          projectId: projectId
        }
      });
    });
  }

  ionViewWillEnter() {
  }

  getAlarmAccount(projectId) {
    this.dataservice.projectAlarmCount(projectId).subscribe(res => {
      if (res.success) {
        if (res.data >= 1) {
          this.alarmAccount = res.data;
          if (this.alarmAccount >= 100) {
            this.alarmAccount = '99+';
          }
          if (this.needAlarmNotify) {
            this.localNotifications.schedule({
              id: new Date().getTime(),
              text: '您有 ' + this.alarmAccount + ' 条告警待处理',
              data: { secret: 'sss' },
            });
            if (this.cache.defaultVoice && this.cache.defaultVoice.voiceType && this.cache.defaultVoice.voicePath) {
              console.log('进入推送mute', this.cache.defaultVoice)
              const auto = <HTMLAudioElement>document.getElementById('audioBox');
              auto.setAttribute('src', this.cache.defaultVoice.voicePath);
              auto.play();
            }
            this.needAlarmNotify = false;
          }
        } else {
          this.alarmAccount = '';
        }
      } else {
        console.log(res.message);
      }
    });
  }

  ngOnDestroy() {
    this.jpushSubscription.unsubscribe();
    this.subscription.unsubscribe();
    if (this.alarmInterval) {
      clearInterval(this.alarmInterval);
    }
  }

  change(event) {
    this.flag = event.detail.tab;
    this.router.events.subscribe(event => { // 需要放到最后一个执行
      if (event instanceof NavigationEnd) {
        this.url = event.url;
        if (this.url === '/tabs/home') {
          this.tab1Root = this.cache.getCurrentIndexPage();
          this.navCtrl.navigateRoot('/tabs/' + this.tab1Root)
        }
      }
    });
  }

  getAlarm(arr) {
    this.Flag = this.alarmAudioService.changeStatus();
    this.alarmAudioService.mergeList(arr);
    if (!this.Flag) {
      this.Flag = true;
      this.alarmAudioService.audioPlayInit();
    }
  }

}
